package com.market.fleamarket.controller;

import com.market.fleamarket.entity.Cart;
import com.market.fleamarket.entity.User;
import com.market.fleamarket.service.CartService;
import com.market.fleamarket.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/api/carts")
public class CartController {
    @Autowired
    private CartService cartService;

    @Autowired
    private ProductService productService;

    @PostMapping
    public Object addCart(@RequestBody Cart cart, HttpSession session) {
        try {
            User user = (User) session.getAttribute("user");
            if (user == null) {
                throw new RuntimeException("请先登录");
            }

            // 检查库存是否足够
            if (!productService.checkStock(cart.getProduct().getId(), cart.getQuantity())) {
                Map<String, String> response = new HashMap<>();
                response.put("error", "商品库存不足");
                return response;
            }

            cart.setUser(user);
            return cartService.save(cart);
        } catch (Exception e) {
            Map<String, String> response = new HashMap<>();
            response.put("error", e.getMessage());
            return response;
        }
    }

    @GetMapping
    public List<Cart> getAllCarts(HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return new java.util.ArrayList<>();
        }
        return cartService.findByUserId(user.getId());
    }

    @GetMapping("/{id}")
    public Cart getCartById(@PathVariable Long id) {
        return cartService.findById(id).orElse(null);
    }

    @DeleteMapping("/{id}")
    public Map<String, String> deleteCart(@PathVariable Long id, HttpSession session) {
        try {
            User user = (User) session.getAttribute("user");
            if (user == null) {
                throw new RuntimeException("请先登录");
            }

            Cart cart = cartService.findById(id).orElseThrow(() -> new RuntimeException("购物车项目不存在"));

            // 检查是否是当前用户的购物车
            if (!cart.getUser().getId().equals(user.getId())) {
                throw new RuntimeException("无权限删除该购物车项目");
            }

            cartService.deleteById(id);
            return java.util.Collections.singletonMap("message", "删除成功");
        } catch (Exception e) {
            return java.util.Collections.singletonMap("error", e.getMessage());
        }
    }

    @PutMapping("/{id}")
    public Object updateCart(@PathVariable Long id, @RequestBody Map<String, Integer> payload, HttpSession session) {
        try {
            User user = (User) session.getAttribute("user");
            if (user == null) {
                throw new RuntimeException("请先登录");
            }

            Cart cart = cartService.findById(id).orElseThrow(() -> new RuntimeException("购物车项目不存在"));

            // 检查是否是当前用户的购物车
            if (!cart.getUser().getId().equals(user.getId())) {
                throw new RuntimeException("无权限修改该购物车项目");
            }

            // 更新数量
            if (payload.containsKey("quantity")) {
                int quantity = payload.get("quantity");
                if (quantity < 1) {
                    throw new RuntimeException("数量必须大于0");
                }

                // 检查库存是否足够
                if (!productService.checkStock(cart.getProduct().getId(), quantity)) {
                    Map<String, String> response = new HashMap<>();
                    response.put("error", "商品库存不足");
                    return response;
                }

                cart.setQuantity(quantity);
            }

            return cartService.save(cart);
        } catch (Exception e) {
            Map<String, String> response = new HashMap<>();
            response.put("error", e.getMessage());
            return response;
        }
    }

    @PostMapping("/checkout")
    public Object checkout(HttpSession session) {
        try {
            User user = (User) session.getAttribute("user");
            if (user == null) {
                throw new RuntimeException("请先登录");
            }
            return cartService.checkoutCart(user);
        } catch (Exception e) {
            return java.util.Collections.singletonMap("error", e.getMessage());
        }
    }
} 